package com.hk.servlet.admin;

import com.alibaba.fastjson.JSONObject;
import com.hk.model.Admin;
import com.hk.model.vo.Result;
import com.hk.service.IAdminService;
import com.hk.service.impl.AdminServiceImpl;
import com.hk.utils.CharacterEncoding;
import com.hk.utils.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: zhe
 * @Date: 2021/6/5 13:23
 * @Statement: 管理员登录
 */
@WebServlet("/admin/tologin")
public class ToLoginServlet extends HttpServlet {

    /**
     * 登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        统一字符编码
        CharacterEncoding.setCharacterEncodingResp(req,resp,"UTF-8");
        String email = Tool.nullToString(req.getParameter("email"));
        String password = Tool.nullToString(req.getParameter("password"));
//        System.out.println("sdfdsgd"+email);
//        System.out.println("sdfdsgd"+password);
        HttpSession session = req.getSession();
//        检查账户是否存在
        IAdminService iAdminService = new AdminServiceImpl();
        Admin admin = new Admin(email, password);
        Admin admin1 = iAdminService.findByEmailAndPassword(admin);
//        System.out.println("返回的对象："+admin1);
        PrintWriter out = resp.getWriter();
        Result result = new Result();
        if (admin1.getId() == 0) {
            result.setStatus(0);
            result.setMessage("error");
        } else {
//            存储登录账户信息
            session.setAttribute("admin",admin1);
            result.setStatus(1);
            result.setMessage("success");
        }
        String resultJSON = JSONObject.toJSONString(result);
        out.println(resultJSON);
        out.flush();
        out.close();


    }
}
